import { useState, useEffect } from 'react';


export function useClassList(element: HTMLElement) {
  const [classList, set_classList] = useState<string[]>();
  useEffect(() => {
    // 创建一个观察器实例并定义回调函数
    const observer = new MutationObserver((mutationsList) => {
      // 遍历所有发生的变化
      for (let mutation of mutationsList) {
        // 检查是否是类名变化
        if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
          set_classList(prev => {
            const next = Array.from(element.classList);
            if (next.join() === prev?.join()) return prev;
            return next;
          });
        }
      }
    });
    // 配置观察器选项
    const config = {
      attributes: true, // 观察属性变化
      attributeFilter: ['class'], // 只观察class属性
      attributeOldValue: true // 记录旧值
    };
    // 开始观察目标元素
    observer.observe(element, config);
    set_classList(Array.from(element.classList))
    return () => observer.disconnect()
  }, [element]);
  return classList;
}
